<!-- filename: pages/profile/profile.vue (重构版) -->
<template>
  <Header @open-auth-modal="isAuthModalVisible = true" />
  <AuthModal v-if="isAuthModalVisible" @close="handleAuthModalClose" />

  <view class="page-container" style="padding-top: 60px;">
    <view class="content-wrapper">
      
      <!-- 加载或未登录时的占位 -->
      <view v-if="isLoading" class="loading-state">加载中...</view>
      <view v-else-if="!authStore.isLoggedIn" class="login-prompt">
        <h1 class="prompt-title">请先登录</h1>
        <p class="prompt-text">登录后即可查看个人信息、管理您的歌单和收藏。</p>
        <button class="prompt-btn" @click="isAuthModalVisible = true">前往注册 / 登录</button>
      </view>

      <!-- 用户已登录，显示个人信息 -->
      <view v-else-if="profile" class="profile-content">
        
        <!-- 顶部信息卡片 -->
        <view class="profile-header">
          <view class="avatar-wrapper" @click="handleAvatarChange">
            <image 
              v-if="profile && profile.avatar_url"
              :src="profile.avatar_url" 
              class="avatar-image"
              mode="aspectFill"
            />
            <view v-else class="avatar-placeholder">{{ (profile.username || 'U').charAt(0).toUpperCase() }}</view>
    
            <!-- 编辑模式下的覆盖层 -->
            <view v-if="isEditMode" class="avatar-edit-overlay">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d="M14.06 9.02l.92.92L5.92 19H5v-.92l9.06-9.06M17.66 3c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.2-.2-.45-.29-.71-.29zm-3.6 3.19L3 17.25V21h3.75L17.81 9.94l-3.75-3.75z"/></svg>
            </view>
          </view>
          <div class="info-wrapper">
            <input v-if="isEditMode" v-model="editableProfile.username" class="username-input" />
            <h1 v-else class="username">{{ profile.username }}</h1>
            
            <textarea v-if="isEditMode" v-model="editableProfile.bio" class="bio-textarea" placeholder="添加个人简介..." />
            <p v-else class="bio">{{ profile.bio || '暂无简介' }}</p>
          </div>
          <div class="actions-wrapper">
            <button v-if="!isEditMode" class="action-btn" @click="enterEditMode">编辑资料</button>
            <button v-if="isEditMode" class="action-btn save-btn" @click="saveProfile">保存</button>
            <button v-if="isEditMode" class="action-btn cancel-btn" @click="cancelEditMode">取消</button>
          </div>
        </view>

        <!-- 隐身模式开关 (仅在编辑模式下显示) -->
        <view v-if="isEditMode" class="stealth-mode-setting">
          <label for="stealth-switch">隐身模式</label>
          <switch id="stealth-switch" :checked="editableProfile.is_stealth_mode" @change="e => editableProfile.is_stealth_mode = e.detail.value" />
          <p class="stealth-tip">开启后，其他用户将无法在你的主页看到你的歌单和评论。</p>
        </view>

        <!-- 【最终版】标签页导航 -->
        <view class="content-tabs">
          <view class="tab-item" @click="navigateToMessages">
            <text>我的私信</text>
            <view v-if="authStore.unreadCounts.messages > 0" class="tab-badge">
              {{ authStore.unreadCounts.messages }}
            </view>
          </view>
          <view class="tab-item" @click="navigateToNotifications">
            <text>我的通知</text>
            <view v-if="authStore.totalUnreadNotifications > 0" class="tab-badge">
              {{ authStore.totalUnreadNotifications }}
            </view>
          </view>
        </view>

        <!-- “我的评论”现在是一个独立的板块 -->
        <view class="content-section">
          <view class="section-header" @click="activeTab = 'comments'">
            <h2 class="section-title">我的评论</h2>
          </view>
          <view class="section-body">
            <CommentList />
          </view>
        </view>

        <view class="actions-section">
          <button class="change-password-btn" @click="isPasswordModalVisible = true">修改密码</button>
          <button class="logout-btn" @click="handleLogout">退出登录</button>
        </view>
      </view>

    </view>
  </view>
  
  <!-- 新增：修改密码弹窗 -->
  <view v-if="isPasswordModalVisible" class="modal-overlay" @click="isPasswordModalVisible = false">
    <view class="modal-content" @click.stop>
      <h2 class="modal-title">修改密码</h2>
      <view class="modal-body">
        <input type="password" v-model="passwordForm.current_password" placeholder="当前密码" class="modal-input" />
        <input type="password" v-model="passwordForm.new_password" placeholder="新密码 (至少6位)" class="modal-input" />
        <input type="password" v-model="passwordForm.confirm_password" placeholder="确认新密码" class="modal-input" />
        <view v-if="passwordError" class="modal-error">{{ passwordError }}</view>
      </view>
      <view class="modal-actions">
        <button class="modal-btn cancel" @click="isPasswordModalVisible = false">取消</button>
        <button class="modal-btn confirm" @click="submitNewPassword">确认修改</button>
      </view>
    </view>
  </view>

  <Player v-if="playerStore.showPlayer" />
</template>


<script setup>
import { ref, reactive } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { usePlayerStore } from '@/store/player';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import Player from '@/components/Player.vue';
import CommentList from '@/components/Profile/CommentList.vue';

const authStore = useAuthStore();
const playerStore = usePlayerStore();
const isAuthModalVisible = ref(false);

// 【核心修改2】不再需要 API_BASE_URL
// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const profile = ref(null);
const isLoading = ref(true);
const isEditMode = ref(false);
const editableProfile = reactive({
  username: '',
  bio: '',
  is_stealth_mode: false,
});

const isPasswordModalVisible = ref(false);
const passwordForm = reactive({
  current_password: '',
  new_password: '',
  confirm_password: '',
});
const passwordError = ref('');

const activeTab = ref('playlists');

// --- 【核心修改3】重写所有 API 请求函数 ---

const submitNewPassword = async () => {
  passwordError.value = '';
  if (!passwordForm.current_password || !passwordForm.new_password || !passwordForm.confirm_password) {
    passwordError.value = '所有字段均为必填项';
    return;
  }
  if (passwordForm.new_password.length < 6) {
    passwordError.value = '新密码长度不能少于6位';
    return;
  }
  if (passwordForm.new_password !== passwordForm.confirm_password) {
    passwordError.value = '两次输入的新密码不一致';
    return;
  }

  uni.showLoading({ title: '提交中...' });
  try {
    await request({
      url: `/api/me/password`,
      method: 'PUT',
      data: {
        current_password: passwordForm.current_password,
        new_password: passwordForm.new_password,
      },
    });
    uni.showToast({ title: '密码修改成功！', icon: 'success' });
    isPasswordModalVisible.value = false;
  } catch (error) {
    passwordError.value = error?.data?.error || '修改失败';
  } finally {
    uni.hideLoading();
  }
};

const fetchProfile = async () => {
  if (!authStore.isLoggedIn) {
    isLoading.value = false;
    return;
  }
  isLoading.value = true;
  try {
    const data = await request({
      url: `/api/me/profile`,
      method: 'GET'
    });
    profile.value = data;
  } catch (error) {
    console.error("Failed to fetch profile:", error);
  } finally {
    isLoading.value = false;
  }
};

const saveProfile = async () => {
  uni.showLoading({ title: '保存中...' });
  try {
    await request({
      url: `/api/me/profile`,
      method: 'PUT',
      data: editableProfile,
    });
    uni.showToast({ title: '保存成功', icon: 'success' });
    isEditMode.value = false;
    fetchProfile(); // 重新获取最新数据
  } catch (error) {
    const errorMsg = error?.data?.error || '保存失败';
    uni.showToast({ title: errorMsg, icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// --- 无需修改的函数 (除了 handleAvatarChange 中的 URL) ---

const handleAvatarChange = () => {
  if (!isEditMode.value) return;

  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      uni.showLoading({ title: '上传中...' });

      // 【核心修改4】uni.uploadFile 的 URL 也需要去掉 base URL
      uni.uploadFile({
        url: `${import.meta.env.VITE_API_BASE_URL}/api/me/avatar`, // uni.uploadFile 需要完整的 URL
        filePath: tempFilePath,
        name: 'avatar',
        header: {
          'Authorization': `Bearer ${authStore.access_token}`
        },
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (uploadRes.statusCode === 200) {
            uni.showToast({ title: '头像更新成功', icon: 'success' });
            authStore.updateUserProfile({ avatar_url: data.new_avatar_url });
            if (profile.value) {
              profile.value.avatar_url = data.new_avatar_url;
            }
          } else {
            uni.showToast({ title: data.error || '上传失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '网络错误', icon: 'error' });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  });
};

onShow(() => {
  fetchProfile();
  if (authStore.isLoggedIn) {
    authStore.fetchTotalUnreadCounts();
  }
});

const navigateToMessages = () => {
  uni.navigateTo({
    url: '/pages/messages/messages'
  });
};

const navigateToNotifications = () => {
  uni.navigateTo({
    url: '/pages/notifications/notifications'
  });
};

const handleAuthModalClose = () => {
  isAuthModalVisible.value = false;
};

const enterEditMode = () => {
  if (!profile.value) return;
  editableProfile.username = profile.value.username;
  editableProfile.bio = profile.value.bio || '';
  editableProfile.is_stealth_mode = profile.value.is_stealth_mode;
  isEditMode.value = true;
};

const cancelEditMode = () => {
  isEditMode.value = false;
};

const handleLogout = async () => {
  const res = await uni.showModal({
    title: '提示',
    content: '您确定要退出登录吗？',
  });
  if (res.confirm) {
    authStore.clearAuth();
  }
};
</script>

<style scoped lang="scss">
/* 页面和内容容器 */
.page-container {
  display: flex; justify-content: center; width: 100%; min-height: 100vh; background-color: #f8f8f8;
}
.content-wrapper {
  width: 100%; max-width: 800px; padding: 20px;
}

/* 登录提示 */
.login-prompt {
  margin-top: 80px; text-align: center; padding: 40px; background-color: #fff; border-radius: 12px;
}
.prompt-title { font-size: 22px; margin-bottom: 15px; }
.prompt-text { color: #666; margin-bottom: 30px; }
.prompt-btn { background-color: #007aff; color: white; &::after { border: none; } }

/* 个人信息内容 */
.profile-content { width: 100%; }
.profile-header {
  display: flex;
  gap: 20px;
  padding: 25px;
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
}
.avatar-wrapper {
  position: relative; // 为覆盖层定位
  cursor: pointer; // 默认显示手型指针
}
.avatar-edit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

// 只有在编辑模式下，悬浮时才显示覆盖层
.profile-content:has(.username-input) .avatar-wrapper:hover .avatar-edit-overlay {
  opacity: 1;
}
.avatar-placeholder,
.avatar-image {
  width: 80px; height: 80px; border-radius: 50%; background-color: #007aff;
  color: white; display: flex; align-items: center; justify-content: center;
  font-size: 36px; font-weight: bold;
}
.avatar-image {
  background-color: #f0f0f0; /* 图片加载前的占位背景色 */
}
.info-wrapper {
  flex-grow: 1;
  min-width: 0;
}
.username {
  font-size: 24px; font-weight: bold; margin-bottom: 10px;
}
.username-input {
  font-size: 24px; font-weight: bold; border: 1px solid #ddd; border-radius: 6px; padding: 5px 10px; margin-bottom: 10px;
}
.bio {
  font-size: 14px; color: #666;
}
.bio-textarea {
  font-size: 14px; color: #666; border: 1px solid #ddd; border-radius: 6px; padding: 8px 10px; /* 调整内边距使其更协调 */
  width: 100%; box-sizing: border-box; 
  height: 50px; /* <-- 修改：使用固定的 height 替代 min-height */
  resize: vertical; /* <-- 新增：允许用户在垂直方向上手动调整大小 (桌面端有效) */
  line-height: 1.5; /* <-- 新增：改善多行文字的行距 */
}
.actions-wrapper {
  display: flex; flex-direction: column; gap: 10px;
}
.action-btn {
  background-color: #f0f0f0; color: #333; font-size: 14px;
  &.save-btn { background-color: #007aff; color: white; }
  &.cancel-btn { background-color: #e5e5e5; }
}

/* 隐身模式 */
.stealth-mode-setting {
  background-color: #fff; padding: 15px 25px; border-radius: 12px; margin-bottom: 20px;
  label { font-weight: 500; margin-right: 15px; }
  .stealth-tip { font-size: 12px; color: #888; margin-top: 8px; }
}

/* 标签页 */
.content-tabs {
  display: grid; /* 使用 grid 布局，方便平分 */
  grid-template-columns: 1fr 1fr;
  gap: 15px; /* 增加间距 */
  margin-bottom: 20px;
  border-bottom: none; /* 移除底边框 */
}

/* 修改 .tab-item */
.tab-item {
  position: relative;
  padding: 20px; /* 增加内边距，让它像个卡片 */
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  border: none; /* 移除边框 */
  background-color: #fff; /* 白色背景 */
  border-radius: 12px; /* 圆角 */
  text-align: center;
  transition: transform 0.2s;
  
  &:hover {
    transform: translateY(-2px);
  }
}
/* 修改 .tab-badge */
.tab-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #e5245e;
  color: white;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  font-size: 11px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 5px;
  box-sizing: border-box;
}

/* 新增 .content-section 样式 */
.content-section {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
}
.section-header {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}
.section-title {
  font-size: 18px;
  font-weight: 500;
}
.section-body {
  /* CommentList 自身有 padding，这里不需要 */
}


/* 【核心重构】标签页内容区 */
.tab-content {
  background-color: #fff;
  border-radius: 12px;
  /* 移除内边距，让子组件自己控制 */
  /* padding: 20px; */
}


/* 按钮容器，负责提供与上方内容的间距 */
.actions-section {
  margin-top: 40px; /* <-- 修改：增加与上方内容的距离 */
}

/* 统一“修改密码”和“退出登录”按钮的样式 */
.change-password-btn,
.logout-btn {
  width: 100%;
  color: white;
  margin-bottom: 15px; /* 按钮之间的垂直间距 */
  font-size: 16px;     /* 统一字体大小 */
  height: 45px;        /* 统一高度 */
  line-height: 45px;   /* 确保文字垂直居中 */

  /* uni-app 按钮样式重置 */
  &::after {
    border: none;
  }
}

/* 分别定义它们的背景颜色 */
.change-password-btn {
  background-color: #007aff; /* 主题蓝色 */
}

.logout-btn {
  background-color: #e5245e; /* 红色 */
  margin-bottom: 0; /* 最后一个按钮不需要下边距 */
}

/* 【核心重构】为整个 content-wrapper 增加底部留白 */
.content-wrapper {
  width: 100%;
  max-width: 800px;
  padding: 20px;
  padding-bottom: 150px;
}



/* 弹窗通用样式 */
.modal-overlay {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex; align-items: center; justify-content: center;
  z-index: 2000;
}
.modal-content {
  width: 90%; max-width: 400px; background-color: white;
  border-radius: 12px; padding: 20px;
}
.modal-title {
  font-size: 18px; font-weight: bold; text-align: center; margin-bottom: 20px;
}
.modal-input {
  width: 100%; height: 44px; border: 1px solid #ddd; border-radius: 6px;
  padding: 0 12px; margin-bottom: 15px; box-sizing: border-box;
}
.modal-error {
  color: #e5245e; font-size: 14px; text-align: center; margin-bottom: 15px;
}
.modal-actions {
  display: flex; gap: 10px;
}
.modal-btn {
  flex: 1;
  &.cancel { background-color: #f0f0f0; color: #333; }
  &.confirm { background-color: #007aff; color: white; }
}
</style>